package com.fuxin.app.web;

import com.fuxin.app.entity.Article;
import com.fuxin.app.entity.Student;
import com.fuxin.app.error.BusinessException;
import com.fuxin.app.services.ArticleService;
import com.fuxin.app.services.CacheService;
import com.fuxin.app.services.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.net.BindException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class AppServer{

	@Autowired
	StudentService studentService;
	@Autowired
	ArticleService articleService;
	@Autowired
	CacheService cacheService;

    @RequestMapping("hello")
    public Map<String,String> hello(@RequestParam String param){
        Map<String,String> map = new HashMap<>();
        map.put("rpcA",param);
        return map;
    }

	@RequestMapping("testStu")
	public Iterable<Student> testStu(){
		return studentService.studentTest();
	}

	@RequestMapping("testArt")
	public List<Article> testArt(){
		return articleService.articleTest();
	}

	@RequestMapping("testCache")
	public long testCache(int id){
		return cacheService.cache(id);
	}

	@RequestMapping("putSession")
	public Map<String, String> putSession(HttpSession session, String key, String value){
		session.setAttribute(key, value);
		Map<String, String> map = new HashMap<>();
		map.put("id",session.getId());
		map.put(key, value);
		return map;
	}

	@RequestMapping("getSession")
	public Map<String, String> getSession(HttpSession session, String key){
		Map<String, String> map = new HashMap<>();
		map.put("id",session.getId());
		map.put(key, session.getAttribute(key).toString());
		return map;
	}

	@RequestMapping("testError")
	public Map<String, String> testError(HttpSession session){
		Map<String, String> map = new HashMap<>();
		if(true){
			throw new BusinessException(403, "测试错误");
		}
		return map;
	}
}
